<template>
    <div class="tetris-container">
        <div class="left-column">
            <div class="score-panel">
                <h3>游戏数据</h3>
                <div class="stat-item">
                    <span class="stat-label">分数:</span>
                    <span class="stat-value">{{ score }}</span>
                </div>
                <div class="stat-item">
                    <span class="stat-label">等级:</span>
                    <span class="stat-value">{{ level }}</span>
                </div>
                <div class="stat-item">
                    <span class="stat-label">消除行数:</span>
                    <span class="stat-value">{{ lines }}</span>
                </div>
            </div>
            <div class="instructions">
                <h3>操作说明</h3>
                <p>← → : 左右移动</p>
                <p>↑ : 旋转方块</p>
                <p>↓ : 加速下落</p>
                <p>空格 : 直接落到底部</p>
            </div>
        </div>
        
        <div class="game-container">
            <div id="tetris-game"></div>
        </div>
        
        <div class="right-column">
            <div class="next-piece-panel">
                <h3>下一个方块</h3>
                <div id="next-piece-preview"></div>
            </div>
            <div class="controls">
                <button @click="startGame" :disabled="gameStarted && !gameOver" class="start-btn">{{ gameOver ? "重新开始" : "开始游戏" }}</button>
                <button @click="pauseGame" :disabled="!gameStarted || gameOver" class="pause-btn">{{ paused ? "继续" : "暂停" }}</button>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
import { ref, onMounted, onUnmounted } from "vue";
import Phaser from "phaser";

export default {
    name: "TetrisGame",
    setup() {
        const score = ref(0);
        const level = ref(1);
        const lines = ref(0);
        const gameStarted = ref(false);
        const paused = ref(false);
        const gameOver = ref(false);

        let game = null;
        let mainScene = null;
        let previewScene = null;

        // 游戏主场景
        class TetrisScene extends Phaser.Scene {
            private board: number[][];
            private currentPiece: any;
            private nextPiece: any;
            private blockSize: number;
            private dropTimer: number;
            private dropSpeed: number;
            private gameStarted: boolean;
            private paused: boolean;
            private gameOver: boolean;
            private cursors: Phaser.Types.Input.Keyboard.CursorKeys | null;
            private spaceKey: Phaser.Input.Keyboard.Key | null;
            private dropFast: boolean;
            private grid: Phaser.GameObjects.Graphics | null;
            private blocks: any[];
            private shadowBlocks: any[];
            private gameOverElements: any[];
            private keyRepeatDelay: number;
            private horizontalMoveTimer: number;
            private isLeftKeyDown: boolean;
            private isRightKeyDown: boolean;
            private horizontalMoveSpeed: number;
            private isHorizontalMoving: boolean;
            private horizontalMoveCount: number;
            private tetrominoes: any[];

            constructor() {
                super("TetrisScene");
                this.board = Array(20)
                    .fill(0)
                    .map(() => Array(12).fill(0));
                this.currentPiece = null;
                this.nextPiece = null;
                this.blockSize = 30;
                this.dropTimer = 0;
                this.dropSpeed = 1000; // 初始下落速度，毫秒
                this.gameStarted = false;
                this.paused = false;
                this.gameOver = false;
                this.cursors = null;
                this.spaceKey = null;
                this.dropFast = false;
                this.grid = null;
                this.blocks = [];
                this.shadowBlocks = [];
                this.gameOverElements = []; // 存储游戏结束时创建的UI元素
                
                // 添加长按移动相关属性
                this.keyRepeatDelay = 200; // 首次按下按键到重复触发的延迟(毫秒)，增加到200毫秒
                this.horizontalMoveTimer = 0; // 水平移动计时器
                this.isLeftKeyDown = false; // 左键是否按下
                this.isRightKeyDown = false; // 右键是否按下
                this.horizontalMoveSpeed = 1000; // 初始水平移动速度，与下落速度一致
                this.isHorizontalMoving = false; // 是否正在水平移动
                this.horizontalMoveCount = 0; // 连续水平移动次数

                // 俄罗斯方块形状定义
                this.tetrominoes = [
                    {
                        // I
                        shape: [
                            [0, 0, 0, 0],
                            [1, 1, 1, 1],
                            [0, 0, 0, 0],
                            [0, 0, 0, 0],
                        ],
                        color: 0x4dc4ff, // 更亮的青色
                    },
                    {
                        // O
                        shape: [
                            [1, 1],
                            [1, 1],
                        ],
                        color: 0xffc857, // 更亮的黄色
                    },
                    {
                        // T
                        shape: [
                            [0, 1, 0],
                            [1, 1, 1],
                            [0, 0, 0],
                        ],
                        color: 0xbb86fc, // 亮紫色
                    },
                    {
                        // S
                        shape: [
                            [0, 1, 1],
                            [1, 1, 0],
                            [0, 0, 0],
                        ],
                        color: 0x4ade80, // 亮绿色
                    },
                    {
                        // Z
                        shape: [
                            [1, 1, 0],
                            [0, 1, 1],
                            [0, 0, 0],
                        ],
                        color: 0xff6b6b, // 亮红色
                    },
                    {
                        // J
                        shape: [
                            [1, 0, 0],
                            [1, 1, 1],
                            [0, 0, 0],
                        ],
                        color: 0x4d94ff, // 亮蓝色
                    },
                    {
                        // L
                        shape: [
                            [0, 0, 1],
                            [1, 1, 1],
                            [0, 0, 0],
                        ],
                        color: 0xff9f4d, // 亮橙色
                    },
                ];
            }

            preload() {
                // 音频已移除
            }

            create() {
                // 创建网格
                this.createGrid();
                
                // 音频已移除
                
                // 设置输入
                this.cursors = this.input.keyboard.createCursorKeys();
                this.spaceKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE);
                
                // 启用键盘输入事件
                this.input.keyboard.on('keydown', this.handleKeyDown, this);
                this.input.keyboard.on('keyup', this.handleKeyUp, this);
                
                // 初始化游戏，但不生成方块
                this.initializeGame();
                
                // 暂停游戏，等待开始
                this.scene.pause();
            }

            initializeGame() {
                // 清空面板
                this.board = Array(20)
                    .fill(0)
                    .map(() => Array(12).fill(0));
                this.drawBoard();
                
                // 重置分数
                score.value = 0;
                level.value = 1;
                lines.value = 0;
                
                // 重置游戏状态
                this.gameStarted = false;
                this.gameOver = false;
                gameOver.value = false;
                this.paused = false;
                this.dropFast = false;
                this.dropSpeed = 1000;
                
                // 重置长按相关状态
                this.isLeftKeyDown = false;
                this.isRightKeyDown = false;
                this.horizontalMoveTimer = 0;
                this.isHorizontalMoving = false;
                this.horizontalMoveCount = 0;
                
                // 预先生成下一个方块，但不在棋盘上显示
                if (!this.nextPiece) {
                    const index = Math.floor(Math.random() * this.tetrominoes.length);
                    this.nextPiece = {
                        shape: [...this.tetrominoes[index].shape.map((row) => [...row])],
                        color: this.tetrominoes[index].color,
                        x: 4,
                        y: 0,
                    };
                    this.updatePreviewScene();
                }
            }

            resetGame() {
                // 清除游戏结束界面元素
                this.clearGameOverElements();
                
                // 清空面板
                this.board = Array(20)
                    .fill(0)
                    .map(() => Array(12).fill(0));
                this.drawBoard();
                
                // 重置分数
                score.value = 0;
                level.value = 1;
                lines.value = 0;
                
                // 创建当前方块
                this.createFirstPiece();
                
                // 重置游戏状态
                this.gameStarted = true;
                this.gameOver = false;
                gameOver.value = false;
                this.paused = false;
                this.dropFast = false;
                this.dropSpeed = 1000;
                
                // 重置长按相关状态
                this.isLeftKeyDown = false;
                this.isRightKeyDown = false;
                this.horizontalMoveTimer = 0;
                this.isHorizontalMoving = false;
                this.horizontalMoveCount = 0;
            }
            
            createFirstPiece() {
                // 如果有预先生成的下一个方块，使用它
                if (this.nextPiece) {
                    this.currentPiece = this.nextPiece;
                    
                    // 生成新的下一个方块
                    const index = Math.floor(Math.random() * this.tetrominoes.length);
                    this.nextPiece = {
                        shape: [...this.tetrominoes[index].shape.map((row) => [...row])],
                        color: this.tetrominoes[index].color,
                        x: 4,
                        y: 0,
                    };
                    
                    // 通知预览场景更新
                    this.updatePreviewScene();
                } else {
                    // 这种情况不应该发生，但以防万一
                    this.createPiece();
                    return;
                }
                
                // 绘制方块及其阴影
                this.drawPiece();
                this.drawShadowPiece();
            }

            createGrid() {
                const offsetX = 0;
                const offsetY = 0;
                
                // 创建网格背景
                this.grid = this.add.graphics();
                
                // 绘制背景
                this.grid.fillStyle(0x2a2a36, 1); // 更深的灰色背景，与主色调协调
                this.grid.fillRect(offsetX, offsetY, 12 * this.blockSize, 20 * this.blockSize);
                
                // 绘制网格线
                this.grid.lineStyle(1, 0x3a3a46, 0.6); // 更深的网格线
                
                // 绘制水平线
                for (let y = 0; y <= 20; y++) {
                    this.grid.moveTo(offsetX, offsetY + y * this.blockSize);
                    this.grid.lineTo(offsetX + 12 * this.blockSize, offsetY + y * this.blockSize);
                }
                
                // 绘制垂直线
                for (let x = 0; x <= 12; x++) {
                    this.grid.moveTo(offsetX + x * this.blockSize, offsetY);
                    this.grid.lineTo(offsetX + x * this.blockSize, offsetY + 20 * this.blockSize);
                }
                
                this.grid.strokePath();
                
                // 添加边框效果 - 移除上下白边
                const border = this.add.graphics();
                border.lineStyle(2, 0x444, 0.8);
                // 只绘制左右边框，去掉上下白边
                border.beginPath();
                border.moveTo(offsetX, offsetY);
                border.lineTo(offsetX, offsetY + 20 * this.blockSize);
                border.moveTo(offsetX + 12 * this.blockSize, offsetY);
                border.lineTo(offsetX + 12 * this.blockSize, offsetY + 20 * this.blockSize);
                border.strokePath();
            }

            createPiece() {
                // 如果没有下一个方块，随机生成一个
                if (!this.nextPiece) {
                    const index = Math.floor(Math.random() * this.tetrominoes.length);
                    this.nextPiece = {
                        shape: [...this.tetrominoes[index].shape.map((row) => [...row])],
                        color: this.tetrominoes[index].color,
                        x: 4,
                        y: 0,
                    };
                }
                
                // 当前方块设置为下一个方块
                this.currentPiece = this.nextPiece;
                
                // 生成新的下一个方块
                const index = Math.floor(Math.random() * this.tetrominoes.length);
                this.nextPiece = {
                    shape: [...this.tetrominoes[index].shape.map((row) => [...row])],
                    color: this.tetrominoes[index].color,
                    x: 4,
                    y: 0,
                };
                
                // 通知预览场景更新
                this.updatePreviewScene();
                
                // 检查游戏是否结束
                if (this.checkCollision(this.currentPiece)) {
                    this.gameOver = true;
                    gameOver.value = true;
                    this.scene.pause();
                    
                    // 在游戏结束时显示结束信息
                    const gameWidth: number = Number(this.game.config.width);
                    const gameHeight: number = Number(this.game.config.height);
                    
                    // 清除之前可能存在的游戏结束元素
                    this.clearGameOverElements();
                    
                    // 创建一个容器来存放游戏结束的所有元素，并确保它在显示层级的最顶部
                    const gameOverContainer = this.add.container(0, 0);
                    gameOverContainer.setDepth(1000); // 使用一个很大的深度值确保在最顶层
                    this.gameOverElements.push(gameOverContainer);
                    
                    // 添加半透明背景
                    const overlay = this.add.rectangle(
                        gameWidth / 2,
                        gameHeight / 2,
                        gameWidth,
                        gameHeight,
                        0x1e1e2e,
                        0.9
                    );
                    gameOverContainer.add(overlay);
                    
                    // 添加装饰线条
                    const decorLine1 = this.add.rectangle(
                        gameWidth / 2,
                        gameHeight / 2 - 80,
                        gameWidth * 0.7,
                        3,
                        0xff79c6,
                        0.7
                    );
                    gameOverContainer.add(decorLine1);
                    
                    const decorLine2 = this.add.rectangle(
                        gameWidth / 2,
                        gameHeight / 2 + 80,
                        gameWidth * 0.7,
                        3,
                        0xff79c6,
                        0.7
                    );
                    gameOverContainer.add(decorLine2);
                    
                    // 添加游戏结束文本
                    const gameOverText = this.add.text(
                        gameWidth / 2,
                        gameHeight / 2 - 50,
                        '游戏结束',
                        {
                            fontFamily: 'Arial',
                            fontSize: '36px',
                            color: '#ff79c6',
                            fontStyle: 'bold',
                            stroke: '#000000',
                            strokeThickness: 4
                        }
                    ).setOrigin(0.5);
                    gameOverContainer.add(gameOverText);
                    
                    // 添加最终分数文本
                    const finalScoreText = this.add.text(
                        gameWidth / 2,
                        gameHeight / 2 + 10,
                        `最终分数: ${score.value}`,
                        {
                            fontFamily: 'Arial',
                            fontSize: '28px',
                            color: '#50fa7b',
                            stroke: '#000000',
                            strokeThickness: 3
                        }
                    ).setOrigin(0.5);
                    gameOverContainer.add(finalScoreText);
                    
                    // 添加重新开始提示
                    const restartText = this.add.text(
                        gameWidth / 2,
                        gameHeight / 2 + 50,
                        '点击"重新开始"继续游戏',
                        {
                            fontFamily: 'Arial',
                            fontSize: '18px',
                            color: '#f1fa8c',
                            stroke: '#000000',
                            strokeThickness: 2
                        }
                    ).setOrigin(0.5);
                    gameOverContainer.add(restartText);
                    
                    // 添加闪烁效果
                    this.tweens.add({
                        targets: restartText,
                        alpha: { from: 1, to: 0.5 },
                        duration: 800,
                        yoyo: true,
                        repeat: -1
                    });
                }
                
                // 绘制方块和其阴影
                this.drawPiece();
                this.drawShadowPiece();
            }

            updatePreviewScene() {
                if (previewScene) {
                    previewScene.updatePreview(this.nextPiece);
                }
            }

            drawBoard() {
                // 清除所有方块
                this.blocks.forEach((block) => block.destroy());
                this.blocks = [];
                
                // 绘制已落下的方块
                for (let y = 0; y < 20; y++) {
                    for (let x = 0; x < 12; x++) {
                        if (this.board[y][x]) {
                            // 创建方块主体
                            const block = this.add.rectangle(
                                x * this.blockSize + this.blockSize / 2,
                                y * this.blockSize + this.blockSize / 2,
                                this.blockSize - 4,
                                this.blockSize - 4,
                                this.board[y][x]
                            );
                            
                            // 添加高亮效果
                            const highlight = this.add.rectangle(
                                x * this.blockSize + this.blockSize / 2,
                                y * this.blockSize + this.blockSize / 2,
                                this.blockSize - 12,
                                this.blockSize - 12,
                                0xffffff,
                                0.3
                            );
                            
                            this.blocks.push(block);
                            this.blocks.push(highlight);
                        }
                    }
                }
            }

            drawPiece() {
                // 清除当前方块
                this.blocks.forEach((block) => block.destroy());
                this.blocks = [];
                
                // 绘制固定方块
                this.drawBoard();
                
                // 绘制当前移动的方块
                if (this.currentPiece) {
                    const { shape, color, x, y } = this.currentPiece;
                    
                    for (let row = 0; row < shape.length; row++) {
                        for (let col = 0; col < shape[row].length; col++) {
                            if (shape[row][col]) {
                                // 创建方块主体
                                const block = this.add.rectangle(
                                    (x + col) * this.blockSize + this.blockSize / 2,
                                    (y + row) * this.blockSize + this.blockSize / 2,
                                    this.blockSize - 4,
                                    this.blockSize - 4,
                                    color
                                );
                                
                                // 添加高亮效果
                                const highlight = this.add.rectangle(
                                    (x + col) * this.blockSize + this.blockSize / 2,
                                    (y + row) * this.blockSize + this.blockSize / 2,
                                    this.blockSize - 12,
                                    this.blockSize - 12,
                                    0xffffff,
                                    0.3
                                );
                                
                                this.blocks.push(block);
                                this.blocks.push(highlight);
                            }
                        }
                    }
                }
            }

            drawShadowPiece() {
                // 清除阴影方块
                this.shadowBlocks.forEach((block) => block.destroy());
                this.shadowBlocks = [];
                
                if (this.currentPiece) {
                    // 复制当前方块
                    const shadowPiece = {
                        shape: this.currentPiece.shape,
                        color: this.currentPiece.color,
                        x: this.currentPiece.x,
                        y: this.currentPiece.y,
                    };
                    
                    // 计算阴影位置（下降到底部）
                    while (!this.checkCollision({ ...shadowPiece, y: shadowPiece.y + 1 })) {
                        shadowPiece.y++;
                    }
                    
                    // 如果阴影不是当前位置，才绘制
                    if (shadowPiece.y !== this.currentPiece.y) {
                        const { shape, x, y } = shadowPiece;
                        
                        for (let row = 0; row < shape.length; row++) {
                            for (let col = 0; col < shape[row].length; col++) {
                                if (shape[row][col]) {
                                    const block = this.add.rectangle(
                                        (x + col) * this.blockSize + this.blockSize / 2,
                                        (y + row) * this.blockSize + this.blockSize / 2,
                                        this.blockSize - 6,
                                        this.blockSize - 6,
                                        this.currentPiece.color,
                                        0.2
                                    );
                                    
                                    // 添加轮廓
                                    const outline = this.add.rectangle(
                                        (x + col) * this.blockSize + this.blockSize / 2,
                                        (y + row) * this.blockSize + this.blockSize / 2,
                                        this.blockSize - 4,
                                        this.blockSize - 4,
                                        this.currentPiece.color,
                                        0.1
                                    );
                                    outline.setStrokeStyle(1, this.currentPiece.color, 0.2); // 降低轮廓透明度
                                    
                                    this.shadowBlocks.push(block);
                                    this.shadowBlocks.push(outline);
                                }
                            }
                        }
                    }
                }
            }

            update(time, delta) {
                if (!this.gameStarted || this.paused || this.gameOver) return;
                
                // 根据等级调整下落速度
                const dropInterval = this.dropFast ? 50 : this.dropSpeed / (1 + (level.value - 1) * 0.2);
                
                // 同时调整水平移动速度，比下落速度快一些以保证流畅的水平移动
                this.horizontalMoveSpeed = Math.min(200, dropInterval / 3);
                
                // 处理左右移动的长按功能，并获取是否成功移动的结果
                const didHorizontalMove = this.handleKeyHolding(delta);
                
                // 只有在成功进行水平移动时才暂停下落
                if (!didHorizontalMove) {
                    // 方块下落
                    this.dropTimer += delta;
                    if (this.dropTimer > dropInterval) {
                        this.dropTimer = 0;
                        this.moveDown();
                    }
                } else {
                    // 在水平移动后重置下落计时器，避免快速下落
                    this.dropTimer = 0;
                }
                
                // 处理单次按键输入
                if (Phaser.Input.Keyboard.JustDown(this.cursors.left)) {
                    this.moveLeft();
                    this.isLeftKeyDown = true;
                    this.horizontalMoveTimer = 0; // 重置计时器，开始长按计时
                    this.isHorizontalMoving = true;
                } else if (Phaser.Input.Keyboard.JustDown(this.cursors.right)) {
                    this.moveRight();
                    this.isRightKeyDown = true;
                    this.horizontalMoveTimer = 0; // 重置计时器，开始长按计时
                    this.isHorizontalMoving = true;
                } else if (Phaser.Input.Keyboard.JustDown(this.cursors.up)) {
                    this.rotate();
                } else if (Phaser.Input.Keyboard.JustDown(this.spaceKey)) {
                    this.hardDrop();
                }
                
                // 检测按键释放
                if (Phaser.Input.Keyboard.JustUp(this.cursors.left)) {
                    this.isLeftKeyDown = false;
                    if (!this.isRightKeyDown) {
                        this.isHorizontalMoving = false;
                        this.horizontalMoveCount = 0;
                    }
                }
                if (Phaser.Input.Keyboard.JustUp(this.cursors.right)) {
                    this.isRightKeyDown = false;
                    if (!this.isLeftKeyDown) {
                        this.isHorizontalMoving = false;
                        this.horizontalMoveCount = 0;
                    }
                }
                
                // 检查是否正在按下下键
                if (this.cursors.down.isDown !== this.dropFast) {
                    this.dropFast = this.cursors.down.isDown;
                }
            }
            
            // 处理长按键盘按键
            handleKeyHolding(delta) {
                let didMove = false;
                
                // 更新水平移动计时器
                if (this.isLeftKeyDown || this.isRightKeyDown) {
                    this.horizontalMoveTimer += delta;
                }
                
                // 如果超过初始延迟，且达到了重复间隔，尝试执行移动
                if (this.horizontalMoveTimer > this.keyRepeatDelay && 
                    this.horizontalMoveTimer % this.horizontalMoveSpeed < delta) {
                    
                    let attemptedMove = false;
                    let moveSucceeded = false;
                    
                    // 尝试左右移动
                    if (this.isLeftKeyDown && !this.isRightKeyDown) {
                        attemptedMove = true;
                        moveSucceeded = this.moveLeft();
                        if (moveSucceeded) {
                            this.horizontalMoveCount++;
                        }
                    } else if (this.isRightKeyDown && !this.isLeftKeyDown) {
                        attemptedMove = true;
                        moveSucceeded = this.moveRight();
                        if (moveSucceeded) {
                            this.horizontalMoveCount++;
                        }
                    }
                    
                    // 如果尝试了移动但失败了（碰到边界），那么允许下落
                    if (attemptedMove && !moveSucceeded) {
                        return false; // 恢复下落
                    }
                    
                    didMove = moveSucceeded;
                    
                    // 水平移动次数超过阈值后，允许一次下落
                    if (this.horizontalMoveCount >= 6) {
                        this.horizontalMoveCount = 0;
                        return false; // 返回false允许下一帧下落
                    }
                }
                
                return didMove;
            }

            moveLeft() {
                if (!this.currentPiece) return false;
                
                const newPosition = {
                    ...this.currentPiece,
                    x: this.currentPiece.x - 1,
                };
                
                if (!this.checkCollision(newPosition)) {
                    this.currentPiece.x--;
                    this.drawPiece();
                    this.drawShadowPiece();
                    return true; // 移动成功
                }
                return false; // 移动失败
            }

            moveRight() {
                if (!this.currentPiece) return false;
                
                const newPosition = {
                    ...this.currentPiece,
                    x: this.currentPiece.x + 1,
                };
                
                if (!this.checkCollision(newPosition)) {
                    this.currentPiece.x++;
                    this.drawPiece();
                    this.drawShadowPiece();
                    return true; // 移动成功
                }
                return false; // 移动失败
            }

            moveDown() {
                if (!this.currentPiece) return;
                
                const newPosition = {
                    ...this.currentPiece,
                    y: this.currentPiece.y + 1,
                };
                
                if (!this.checkCollision(newPosition)) {
                    this.currentPiece.y++;
                    this.drawPiece();
                    return true;
                } else {
                    this.lockPiece();
                    return false;
                }
            }

            hardDrop() {
                if (!this.currentPiece) return;
                
                while (this.moveDown()) {
                    // 持续下移直到不能移动
                }
            }

            rotate() {
                if (!this.currentPiece) return;
                
                // 获取旋转后的形状
                const rotatedShape = this.getRotatedShape(this.currentPiece.shape);
                
                // 创建旋转后的方块
                const rotatedPiece = {
                    ...this.currentPiece,
                    shape: rotatedShape,
                };
                
                // 尝试旋转，包含墙踢检测
                if (!this.checkCollision(rotatedPiece)) {
                    this.currentPiece.shape = rotatedShape;
                    this.drawPiece();
                    this.drawShadowPiece();
                } else {
                    // 尝试向左墙踢
                    rotatedPiece.x -= 1;
                    if (!this.checkCollision(rotatedPiece)) {
                        this.currentPiece.shape = rotatedShape;
                        this.currentPiece.x -= 1;
                        this.drawPiece();
                        this.drawShadowPiece();
                    } else {
                        // 尝试向右墙踢
                        rotatedPiece.x += 2;
                        if (!this.checkCollision(rotatedPiece)) {
                            this.currentPiece.shape = rotatedShape;
                            this.currentPiece.x += 1;
                            this.drawPiece();
                            this.drawShadowPiece();
                        }
                    }
                }
            }

            getRotatedShape(shape) {
                // 创建新的旋转后的形状
                const rotated = [];
                const n = shape.length;
                
                for (let i = 0; i < n; i++) {
                    rotated.push([]);
                    for (let j = 0; j < n; j++) {
                        rotated[i][j] = shape[n - j - 1][i];
                    }
                }
                
                return rotated;
            }

            checkCollision(piece) {
                const { shape, x, y } = piece;
                
                for (let row = 0; row < shape.length; row++) {
                    for (let col = 0; col < shape[row].length; col++) {
                        if (shape[row][col]) {
                            const boardX = x + col;
                            const boardY = y + row;
                            
                            // 检查边界
                            if (boardX < 0 || boardX >= 12 || boardY >= 20) {
                                return true;
                            }
                            
                            // 检查与已有方块碰撞
                            if (boardY >= 0 && this.board[boardY][boardX]) {
                                return true;
                            }
                        }
                    }
                }
                
                return false;
            }

            lockPiece() {
                if (!this.currentPiece) return;
                
                const { shape, color, x, y } = this.currentPiece;
                
                // 将方块固定到棋盘
                for (let row = 0; row < shape.length; row++) {
                    for (let col = 0; col < shape[row].length; col++) {
                        if (shape[row][col]) {
                            const boardY = y + row;
                            const boardX = x + col;
                            
                            if (boardY >= 0 && boardY < 20 && boardX >= 0 && boardX < 12) {
                                this.board[boardY][boardX] = color;
                            }
                        }
                    }
                }
                
                // 检查消除行
                this.checkLines();
                
                // 创建新方块
                this.createPiece();
            }

            checkLines() {
                let linesCleared = 0;
                
                for (let y = 19; y >= 0; y--) {
                    // 检查一行是否已满
                    if (this.board[y].every((cell) => cell !== 0)) {
                        // 删除该行，在顶部添加新行
                        this.board.splice(y, 1);
                        this.board.unshift(Array(12).fill(0));
                        
                        linesCleared++;
                        
                        // 因为删除了一行，需要再次检查同一行
                        y++;
                    }
                }
                
                if (linesCleared > 0) {
                    // 更新分数
                    lines.value += linesCleared;
                    
                    // 根据消除行数计算分数
                    const lineScores = [0, 100, 300, 500, 800];
                    score.value += lineScores[linesCleared] * level.value;
                    
                    // 每消除10行升一级
                    level.value = Math.floor(lines.value / 10) + 1;
                    
                    // 重新绘制棋盘
                    this.drawBoard();
                }
            }

            // 清除游戏结束时创建的UI元素
            clearGameOverElements() {
                if (this.gameOverElements && this.gameOverElements.length > 0) {
                    this.gameOverElements.forEach(element => {
                        if (element && element.destroy) {
                            element.destroy();
                        }
                    });
                    this.gameOverElements = [];
                }
            }

            // 处理键盘按下事件
            handleKeyDown(event) {
                if (!this.gameStarted || this.paused || this.gameOver) return;
                
                // 在首次按下时执行一次移动并设置按键状态
                if (event.code === 'ArrowLeft') {
                    // 如果已经按下右键，则先释放右键
                    if (this.isRightKeyDown) {
                        this.isRightKeyDown = false;
                    }
                    // 设置左键按下状态
                    this.isLeftKeyDown = true;
                    this.isHorizontalMoving = true;
                    // 如果是刚开始按键，立即移动一次
                    if (this.horizontalMoveTimer === 0) {
                        // 尝试移动，如果不能移动（已到边界），不增加移动次数
                        if (this.moveLeft()) {
                            this.horizontalMoveCount = 1;
                        } else {
                            // 如果移动失败，设置为不在水平移动
                            this.isHorizontalMoving = false;
                        }
                    }
                    // 重置计时器，开始长按倒计时
                    this.horizontalMoveTimer = 0;
                } else if (event.code === 'ArrowRight') {
                    // 如果已经按下左键，则先释放左键
                    if (this.isLeftKeyDown) {
                        this.isLeftKeyDown = false;
                    }
                    // 设置右键按下状态
                    this.isRightKeyDown = true;
                    this.isHorizontalMoving = true;
                    // 如果是刚开始按键，立即移动一次
                    if (this.horizontalMoveTimer === 0) {
                        // 尝试移动，如果不能移动（已到边界），不增加移动次数
                        if (this.moveRight()) {
                            this.horizontalMoveCount = 1;
                        } else {
                            // 如果移动失败，设置为不在水平移动
                            this.isHorizontalMoving = false;
                        }
                    }
                    // 重置计时器，开始长按倒计时
                    this.horizontalMoveTimer = 0;
                }
            }
            
            // 处理键盘释放事件
            handleKeyUp(event) {
                if (event.code === 'ArrowLeft') {
                    this.isLeftKeyDown = false;
                    // 如果右键仍然被按下，重置计时器以便继续处理右键
                    if (this.isRightKeyDown) {
                        this.horizontalMoveTimer = this.keyRepeatDelay + 1;
                        this.isHorizontalMoving = true;
                    } else {
                        this.horizontalMoveTimer = 0;
                        this.isHorizontalMoving = false;
                        this.horizontalMoveCount = 0;
                    }
                } else if (event.code === 'ArrowRight') {
                    this.isRightKeyDown = false;
                    // 如果左键仍然被按下，重置计时器以便继续处理左键
                    if (this.isLeftKeyDown) {
                        this.horizontalMoveTimer = this.keyRepeatDelay + 1;
                        this.isHorizontalMoving = true;
                    } else {
                        this.horizontalMoveTimer = 0;
                        this.isHorizontalMoving = false;
                        this.horizontalMoveCount = 0;
                    }
                }
            }
        }

        // 预览下一个方块的场景
        class PreviewScene extends Phaser.Scene {
            private blockSize: number;
            private nextPiece: any;
            private blocks: any[];
            private grid: Phaser.GameObjects.Graphics | null;

            constructor() {
                super("PreviewScene");
                this.blockSize = 20;
                this.nextPiece = null;
                this.blocks = [];
                this.grid = null;
            }

            create() {
                this.grid = this.add.graphics();
                
                // 绘制背景
                this.grid.fillStyle(0x2a2a36, 1); // 更深的灰色背景，与主色调协调
                this.grid.fillRect(0, 0, 4 * this.blockSize, 4 * this.blockSize);
                
                // 绘制网格
                this.grid.lineStyle(1, 0x3a3a46, 0.4); // 更深的网格线
                
                // 绘制水平线
                for (let y = 0; y <= 4; y++) {
                    this.grid.moveTo(0, y * this.blockSize);
                    this.grid.lineTo(4 * this.blockSize, y * this.blockSize);
                }
                
                for (let x = 0; x <= 4; x++) {
                    this.grid.moveTo(x * this.blockSize, 0);
                    this.grid.lineTo(x * this.blockSize, 4 * this.blockSize);
                }
                
                this.grid.strokePath();
                
                // 移除边框，解决黑边问题
                // 不再添加border
            }

            updatePreview(nextPiece) {
                this.nextPiece = nextPiece;
                this.drawPreview();
            }

            drawPreview() {
                // 清除预览方块
                this.blocks.forEach((block) => block.destroy());
                this.blocks = [];
                
                if (this.nextPiece) {
                    const { shape, color } = this.nextPiece;
                    const offsetX = (4 - shape[0].length) / 2;
                    const offsetY = (4 - shape.length) / 2;
                    
                    for (let row = 0; row < shape.length; row++) {
                        for (let col = 0; col < shape[row].length; col++) {
                            if (shape[row][col]) {
                                // 创建方块主体，调整大小以避免边界问题
                                const block = this.add.rectangle(
                                    (offsetX + col) * this.blockSize + this.blockSize / 2,
                                    (offsetY + row) * this.blockSize + this.blockSize / 2,
                                    this.blockSize - 4,
                                    this.blockSize - 4,
                                    color
                                );
                                
                                // 添加高亮效果，稍微缩小以避免边界问题
                                const highlight = this.add.rectangle(
                                    (offsetX + col) * this.blockSize + this.blockSize / 2,
                                    (offsetY + row) * this.blockSize + this.blockSize / 2,
                                    this.blockSize - 8,
                                    this.blockSize - 8,
                                    0xffffff,
                                    0.3
                                );
                                
                                // 添加小的发光效果，确保不超出边界
                                const glow = this.add.rectangle(
                                    (offsetX + col) * this.blockSize + this.blockSize / 2,
                                    (offsetY + row) * this.blockSize + this.blockSize / 2,
                                    this.blockSize - 2,
                                    this.blockSize - 2,
                                    color,
                                    0.1
                                );
                                
                                this.blocks.push(glow);
                                this.blocks.push(block);
                                this.blocks.push(highlight);
                            }
                        }
                    }
                }
            }
        }

        const startGame = () => {
            if (game && !gameStarted.value || gameOver.value) {
                // 重置游戏状态
                gameStarted.value = true;
                paused.value = false;
                gameOver.value = false;
                
                // 重启主场景
                if (mainScene) {
                    mainScene.resetGame();
                    mainScene.scene.resume();
                }
            }
        };

        const pauseGame = () => {
            if (game && gameStarted.value && !gameOver.value) {
                paused.value = !paused.value;
                
                if (mainScene) {
                    mainScene.paused = paused.value;
                    
                    if (paused.value) {
                        mainScene.scene.pause();
                    } else {
                        mainScene.scene.resume();
                    }
                }
            }
        };

        onMounted(() => {
            // 游戏配置
            const config = {
                type: Phaser.AUTO,
                width: 360, // 恢复为360px
                height: 600,
                parent: "tetris-game",
                scene: [TetrisScene],
                backgroundColor: 0x0000, // 透明背景
                scale: {
                    mode: Phaser.Scale.FIT,
                    autoCenter: Phaser.Scale.CENTER_BOTH,
                },
                transparent: true, // 启用透明度
            };
            
            // 创建游戏实例
            game = new Phaser.Game(config);
            
            // 预览场景配置
            const previewConfig = {
                type: Phaser.AUTO,
                width: 90,
                height: 90,
                parent: "next-piece-preview",
                scene: [PreviewScene],
                backgroundColor: 0x0000, // 透明背景
                scale: {
                    mode: Phaser.Scale.FIT,
                    autoCenter: Phaser.Scale.CENTER_BOTH,
                },
                transparent: true, // 启用透明度
            };
            
            // 创建预览游戏实例
            const previewGame = new Phaser.Game(previewConfig);
            
            // 获取场景引用
            game.events.on("ready", () => {
                mainScene = game.scene.getScene("TetrisScene");
            });
            
            previewGame.events.on("ready", () => {
                previewScene = previewGame.scene.getScene("PreviewScene");
            });
        });

        onUnmounted(() => {
            // 销毁游戏实例
            if (game) {
                game.destroy(true);
                game = null;
            }
        });

        return {
            score,
            level,
            lines,
            gameStarted,
            paused,
            gameOver,
            startGame,
            pauseGame,
        };
    },
};
</script>

<style lang="scss" scoped src="./tetris.scss">
</style>
